import 'dart:io';
import 'package:path/path.dart' as path;

class RenameResult {
  final int successCount;
  final int failCount;

  RenameResult(this.successCount, this.failCount);
}

class RenameService {
  /// 生成新的文件名列表，支持自定义前缀和后缀
  List<String> generateNewFileNames(
      List<FileSystemEntity> files, int startNumber,
      {String prefix = '', String suffix = ''}) {
    return List.generate(files.length, (index) {
      String originalName = path.basename(files[index].path);
      String extension = path.extension(originalName); // 获取原始扩展名
      return '$prefix${startNumber + index}${suffix.isEmpty ? extension : suffix}';
    });
  }

  /// 执行文件重命名操作
  Future<RenameResult> renameFiles(
      List<FileSystemEntity> files, int startNumber,
      {String prefix = '', String suffix = ''}) async {
    int successCount = 0;
    int failCount = 0;

    for (int i = 0; i < files.length; i++) {
      File file = files[i] as File;
      String directory = path.dirname(file.path);
      String extension = path.extension(file.path);
      String newName =
          '$prefix${startNumber + i}${suffix.isEmpty ? extension : suffix}'; // 使用自定义前缀和后缀
      String newPath = path.join(directory, newName);

      try {
        await file.rename(newPath);
        successCount++;
      } catch (e) {
        failCount++;
      }
    }

    return RenameResult(successCount, failCount);
  }
}
